import {plugin} from '../../api/api.js';
import config from '../../model/Config.js';
import data from '../../model/XiuxianData.js';
import {
  player_efficiency,
  Read_player,
  existplayer,
  isNotNull,
  exist_najie_thing,
  Add_najie_thing,
  Add_血气,
  Add_修为,
  Read_danyao,
  Write_danyao,
  setFileValue,
} from '../../model/xiuxian.js';

/**
 * 定时任务
 */

export class PlayerControl extends plugin {
  constructor() {
    super({
      name: 'PlayerControl',
      dsc: '控制人物的行为',
      event: 'message',
      priority: 600,
      rule: [
        {
          reg: '^闭关$',
          fnc: 'Biguan',
        },
        {
          reg: '^锻体$',
          fnc: 'duanti',
        },
        {
          reg: '^出关$',
          fnc: 'chuGuan',
        },
        {
          reg: '^凝脉$',
          fnc: 'ningmai',
        },
        {
          reg: '^修炼$',
          fnc: 'cultivate',
        },
        {
          reg: '^结束修炼$',
          fnc: 'endCultivate',
        },
      ],
    });
    this.xiuxianConfigData = config.getConfig('xiuxian', 'xiuxian');
  }

  //闭关
  async Biguan(e) {
    let usr_qq = e.user_id; //用户qq
    //有无存档      
    if (!(await existplayer(usr_qq))) {
      return;
    }

    //不开放私聊
    if (!e.isGroup) {
      return;
    }

    //获取游戏状态
    let game_action = await redis.get(
      'xiuxian:player:' + usr_qq + ':game_action'
    );
    //防止继续其他娱乐行为
    if (game_action == 0) {
      e.reply('忙其他事呢...');
      return;
    }

    //查询redis中的人物动作
    let action = await redis.get('xiuxian:player:' + usr_qq + ':action');
    action = JSON.parse(action);
    let now_time = new Date().getTime();
    if (action != null) {
      if(null != action.start_time){
        let time = now_time - action.start_time
        let days = parseInt(time / (1000 * 60 * 60 * 24));
        let hours = parseInt((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        let minutes = parseInt((time % (1000 * 60 * 60)) / (1000 * 60));
        e.reply(action.action +` ` + days +` 天 `+ hours +` 小时 ` + minutes +` 分钟 `);
        return;
      }else{
        if (null != action.end_time){
          let action_end_time = action.end_time;
          if (now_time <= action_end_time) {
            let m = parseInt((action_end_time - now_time) / 1000 / 60);
            let s = parseInt((action_end_time - now_time - m * 60 * 1000) / 1000);
            e.reply(`正在` + action.action + '中，剩余时间:' + m + '分' + s + '秒');
            return;
          }
        }
      }
    }
    let arr = {
      action: '闭关', //动作
      start_time: now_time,
    };
    if (e.isGroup) {
      arr.group_id = e.group_id;
    }

    await redis.set(
        'xiuxian:player:' + usr_qq + ':action',
        JSON.stringify(arr)
    ); //redis设置动作
    e.reply(`现在开始闭关`);
    return true;
  }
  //锻体
  async duanti(e) {
    let usr_qq = e.user_id; //用户qq
    //有无存档      
    if (!(await existplayer(usr_qq))) {
      return;
    }

    //不开放私聊
    if (!e.isGroup) {
      return;
    }

    //获取游戏状态
    let game_action = await redis.get(
      'xiuxian:player:' + usr_qq + ':game_action'
    );
    //防止继续其他娱乐行为
    if (game_action == 0) {
      e.reply('忙其他事呢...');
      return;
    }

    //查询redis中的人物动作
    let action = await redis.get('xiuxian:player:' + usr_qq + ':action');
    action = JSON.parse(action);
    let now_time = new Date().getTime();
    if (action != null) {
      if(null != action.start_time){
        let time = now_time - action.start_time
        let days = parseInt(time / (1000 * 60 * 60 * 24));
        let hours = parseInt((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        let minutes = parseInt((time % (1000 * 60 * 60)) / (1000 * 60));
        e.reply(action.action +` ` + days +` 天 `+ hours +` 小时 ` + minutes +` 分钟 `);
        return;
      }else{
        if (null != action.end_time){
          let action_end_time = action.end_time;
          if (now_time <= action_end_time) {
            let m = parseInt((action_end_time - now_time) / 1000 / 60);
            let s = parseInt((action_end_time - now_time - m * 60 * 1000) / 1000);
            e.reply(`正在` + action.action + '中，剩余时间:' + m + '分' + s + '秒');
            return;
          }
        }
      }
    }
    let arr = {
      action: '锻体', //动作
      start_time: now_time,
    };
    if (e.isGroup) {
      arr.group_id = e.group_id;
    }

    await redis.set(
        'xiuxian:player:' + usr_qq + ':action',
        JSON.stringify(arr)
    ); //redis设置动作
    e.reply(`现在开始锻体`);
    return true;
  }

  
  /**
   * 人物结束闭关
   * @param e
   * @returns {Promise<void>}
   */
  async chuGuan(e) {
    //不开放私聊功能
    if (!e.isGroup) {
      return;
    }
    let usr_qq = e.user_id;
    let ifExistPlay = await existplayer(usr_qq);
    if (!ifExistPlay) {
      return;
    }
    let action = await this.getPlayerAction(usr_qq);
    if (!isNotNull(action) || "闭关" !== action.action) {
      e.reply('不在闭关状态');
      return;
    }
    //结算
    let time;
    let now_time = new Date().getTime();
    if (null != action.start_time) {
      //属于提前结束
      time = parseInt( (now_time -action.start_time)/1000/60);
    }else {
      let start_time = action.end_time - action.time;
      time = parseInt((now_time - start_time) / 1000 / 60);
    }

    await player_efficiency(usr_qq);
    let player = data.getData('player', usr_qq);
    let now_level_id;
    if (!isNotNull(player.level_id)) {
      return;
    }
    now_level_id = data.Level_list.find(
        item => item.level_id == player.level_id
    ).level_id;
    //闭关收益倍率计算 倍率*境界id*天赋*时间
    var size = this.xiuxianConfigData.biguan.size;
    //增加的修为
    let xiuwei = parseInt(size * now_level_id * (player.修炼效率提升 + 1));
    //恢复的血量
    let blood = parseInt(player.血量上限 * 0.01);
    //额外修为
    let other_xiuwei = 0;

    let msg = [segment.at(usr_qq)];
    //炼丹师丹药修正
    let transformation = '修为';
    let xueqi = 0;
    let dy = await Read_danyao(usr_qq);
    if (dy.biguan > 0) {
      dy.biguan--;
      if (dy.biguan == 0) {
        dy.biguanxl = 0;
      }
    }
    if (dy.lianti > 0) {
      transformation = '血气';
      dy.lianti--;
    }
    //随机事件预留空间
    let is_random =false;
    if(0.3 > Math.random()){
      is_random = true;
    }

    if (is_random) {
      let rand = Math.random();
      //顿悟
      if (rand < 0.2) {
        rand = Math.trunc(rand * 10) + 45;
        other_xiuwei = Math.trunc(rand * time);
        xueqi = Math.trunc(rand * time * dy.beiyong4);
        if (transformation == '血气') {
          msg.push(`\n本次闭关顿悟,受到炼神之力,额外增加[血气]:` + xueqi);
          msg.push(`\n本次闭关顿悟,额外增加[修为]:` + other_xiuwei);
        } else {
          msg.push(`\n本次闭关顿悟,额外增加[修为]:` + other_xiuwei);
        }
      }
      //走火入魔
      else if (rand > 0.8) {
        rand = Math.trunc(rand * 10) + 5;
        other_xiuwei = Math.trunc(-1 * rand * time);
        xueqi = Math.trunc(rand * time * dy.beiyong4);
        if (transformation == '血气') {
          msg.push(
              `\n,走火入魔,[血气]下降` +
              xueqi
          );
          msg.push(
            `\n差点走火入魔,[修为]` + other_xiuwei
        );
        } else {
          msg.push(
              `\n不小心走火入魔,[修为]` + other_xiuwei
          );
        }
      }
    }
    let other_x = 0;
    let qixue = 0;
    if (
        (await exist_najie_thing(usr_qq, '魔界秘宝', '道具')) &&
        player.魔道值 > 999
    ) {
      other_x = Math.trunc(xiuwei * 0.15 * time);
      await Add_najie_thing(usr_qq, '魔界秘宝', '道具', -1);
      msg.push(`\n消耗了道具[魔界秘宝],额外增加` + other_x + '修为');
      await Add_修为(usr_qq, other_x);
    }
    if (
        (await exist_najie_thing(usr_qq, '神界秘宝', '道具')) &&
        player.魔道值 < 1 &&
        (player.灵根.type == '转生' || player.level_id > 41)
    ) {
      qixue = Math.trunc(xiuwei * 0.1 * time);
      await Add_najie_thing(usr_qq, '神界秘宝', '道具', -1);
      msg.push(`\n消耗了道具[神界秘宝],额外增加` + qixue + '血气');
      await Add_血气(usr_qq, qixue);
    }
    //设置修为，设置血量

    await setFileValue(usr_qq, Math.trunc(blood * time), '当前血量');

    //给出消息提示
    if (transformation == '血气') {
      let xueqi = Math.trunc((xiuwei * time + other_xiuwei) * dy.beiyong4)
      await setFileValue(
          usr_qq,
          xueqi,
          transformation
      ); //丹药修正
      await setFileValue(usr_qq, xueqi, '修为');
      msg.push(
          `\n受到炼神之力的影响,增加血气:` + xueqi,
          `\n同时增加修为:` + xueqi,
          '\n恢复血量:' + blood * time
      );
    } else {
      let xueqi = Math.trunc(xiuwei * time + other_xiuwei)
      await setFileValue(usr_qq, xueqi, transformation);
      if (is_random) {
        msg.push(
            `\n增加修为:` + xueqi,
            '\n恢复血量:' + blood * time 
        );
      } else {
        msg.push(
            `\n增加修为:` + xueqi,
            '\n恢复血量:' + blood * time
        );
      }
    }
    e.reply(msg);
    if (dy.lianti <= 0) {
      dy.lianti = 0;
      dy.beiyong4 = 0;
    }
    //炼丹师修正结束
    await Write_danyao(usr_qq, dy);
    //把状态都关了
    await  redis.del('xiuxian:player:' + usr_qq + ':action');
    return;
  }

  /**
   * 人物结束锻体
   * @param e
   * @returns {Promise<void>}
   */
  async ningmai(e) {
    //不开放私聊功能
    if (!e.isGroup) {
      return;
    }
    let usr_qq = e.user_id;
    let ifExistPlay = await existplayer(usr_qq);
    if (!ifExistPlay) {
      return;
    }
    let action = await this.getPlayerAction(usr_qq);
    if (!isNotNull(action) || "锻体" !== action.action) {
      e.reply('不在锻体状态');
      return;
    }
    //结算
    let time;
    let now_time = new Date().getTime();
    if (null != action.start_time) {
      //属于提前结束
      time = parseInt( (now_time -action.start_time)/1000/60);
    }else {
      let start_time = action.end_time - action.time;
      time = parseInt((now_time - start_time) / 1000 / 60);
    }

    await player_efficiency(usr_qq);
    let player = data.getData('player', usr_qq);
    let now_level_id;
    if (!isNotNull(player.level_id)) {
      return;
    }
    now_level_id = data.LevelMax_list.find(
        item => item.level_id == player.Physique_id
    ).level_id;
    //闭关收益倍率计算 倍率*境界id*天赋*时间
    var size = this.xiuxianConfigData.biguan.size;
    //增加的修为
    let xiuwei = parseInt(size * now_level_id * (player.修炼效率提升 + 1));
    //恢复的血量
    let blood = parseInt(player.血量上限 * 0.01);
    //额外修为
    let other_xiuwei = 0;

    let msg = [segment.at(usr_qq)];
  
 
    let xueqi = 0;
    //随机事件预留空间
    let is_random =false;
    if(0.3 > Math.random()){
      is_random = true;
    }

    if (is_random) {
      let rand = Math.random();
      //顿悟
      if (rand < 0.2) {
        rand = Math.trunc(rand * 10) + 45;
        other_xiuwei = Math.trunc(rand * time);
        
        msg.push(`\n本次锻体顿悟,额外增加[气血]:` + other_xiuwei);
        
      }
      //走火入魔
      else if (rand > 0.8) {
        rand = Math.trunc(rand * 10) + 5;
        other_xiuwei = Math.trunc(-1 * rand * time);
        xueqi = Math.trunc(rand * time );
          msg.push(
              `\n不小心走火入魔,[气血]` + other_xiuwei
          );
        
      }
    }
    //设置修为，设置血量

    await setFileValue(usr_qq, Math.trunc(blood * time), '当前血量');

    //给出消息提示
      
       xiuwei = Math.trunc(xiuwei * time + other_xiuwei)
       await setFileValue(usr_qq, xiuwei, '血气');
      if (is_random) {
        msg.push(
            `\n增加气血:` + xiuwei,
            '\n恢复血量:' + blood * time 
        );
      } else {
        msg.push(
            `\n增加气血:` + xiuwei,
            '\n恢复血量:' + blood * time
        );
      }
    
    e.reply(msg);

  
    //把状态都关了
    await  redis.del('xiuxian:player:' + usr_qq + ':action');
    return;
  }
  async cultivate(e) {
    let usr_qq = e.user_id; // 用户QQ
    // 检查玩家是否有存档
    if (!(await existplayer(usr_qq))) {
      e.reply('你还没有角色，请先创建角色！');
      return;
    }
  
    // 不开放私聊
    if (!e.isGroup) {
      e.reply('修炼功能仅限群聊中使用！');
      return;
    }
  
    // 检查玩家是否正在进行其他动作
    let action = await redis.get('xiuxian:player:' + usr_qq + ':action');
    if (action) {
      e.reply('你正在进行其他活动，无法修炼！');
      return;
    }
  
    // 设置修炼状态
    let now_time = new Date().getTime();
    let arr = {
      action: '修炼',
      start_time: now_time,
    };
    await redis.set('xiuxian:player:' + usr_qq + ':action', JSON.stringify(arr));
    e.reply('开始修炼，1分钟后将获得奖励！');
  
    // 倒计时1分钟后结算奖励
    setTimeout(async () => {
      // 检查玩家是否仍在修炼状态
      let current_action = await redis.get('xiuxian:player:' + usr_qq + ':action');
      if (!current_action || JSON.parse(current_action).action !== '修炼') {
        return;
      }
  
      // 获取玩家数据
      let player = data.getData('player', usr_qq);
      let base_reward = 200; // 基础奖励
      let efficiency = 1 + player.修炼效率提升 || 1; // 修炼效率加成
      let reward1 = Math.trunc(base_reward * efficiency * player.level_id);
      let reward2 = Math.trunc(base_reward * efficiency * player.Physique_id);
      console.log(`值为: ${player.race}`);
  
      // 根据种族属性增加血气或修为
      if (player.race === 1) {
        // 妖族增加血气
        await Add_血气(usr_qq, reward2);
        e.reply(`修炼完成！你获得了 ${reward2} 点血气！`);
      } else if (player.race === 2) {
        // 人族增加修为
        await Add_修为(usr_qq, reward1);
        e.reply(`修炼完成！你获得了 ${reward1} 点修为！`);
      } else {
        e.reply('未知种族，无法修炼！');
      }
  
      // 清除修炼状态
      await redis.del('xiuxian:player:' + usr_qq + ':action');
    }, 60000); // 1分钟 = 60000毫秒
  }

  async endCultivate(e) {
    let usr_qq = e.user_id; // 用户QQ
    // 检查玩家是否有存档
    if (!(await existplayer(usr_qq))) {
      e.reply('你还没有角色，请先创建角色！');
      return;
    }

    // 不开放私聊
    if (!e.isGroup) {
      e.reply('结束修炼功能仅限群聊中使用！');
      return;
    }

    // 检查玩家是否正在修炼
    let action = await redis.get('xiuxian:player:' + usr_qq + ':action');
    if (!action || JSON.parse(action).action !== '修炼') {
      e.reply('你当前没有在修炼！');
      return;
    }

   

    // 清除修炼状态
    await redis.del('xiuxian:player:' + usr_qq + ':action');

    // 回复奖励信息
    e.reply(`修炼结束！么有获得奖励！`);
  }

  /**
   * 获取缓存中的人物状态信息
   * @param usr_qq
   * @returns {Promise<void>}
   */
  async getPlayerAction(usr_qq) {
    let action = await redis.get('xiuxian:player:' + usr_qq + ':action');
    action = JSON.parse(action); //转为json格式数据
    return action;
  }
}
